package com.health.controller;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import com.health.domain.dto.LoginDTO;
import com.health.domain.pojo.User;
import com.health.domain.vo.Result;
import com.health.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

/**
 * @author ghy
 * @version 1.0
 * @since 2025-06-20 17:01
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 登录接口
     * @param loginDTO 登录请求实体
     * @return 登录成功的Result
     */
    @PostMapping("/login")
    public Result<String> login(@RequestBody LoginDTO loginDTO){
        log.info("{}", loginDTO);
        // 调用业务层去处理登录的逻辑
        User user = userService.login(loginDTO);
        // 3.如果合理，那么才是登录成功。把登录的用户信息存储起来
        String uuid = UUID.randomUUID().toString();
        stringRedisTemplate.opsForValue().set("backend_login_user_" + uuid, user.getUsername());
        return Result.success(uuid);
    }

    @GetMapping("/getUsername")
    public Result<String> getUsername(String uuid){
        String username = stringRedisTemplate.opsForValue().get("backend_login_user_" + uuid);
        if(StrUtil.isBlank(username)) {
            throw new RuntimeException("非法用户");
        }
        return Result.success(username);
    }


}
